//
//  MineViewController.m
//  DaleTou
//
//  Created by hejingjin on 2018/5/27.
//  Copyright © 2018年 geren. All rights reserved.
//

#import "MineViewController.h"
#import "UIImage+Color.h"
#import "ShareValue.h"
#import "OrderBillViewController.h"
#import "SystemAlertView.h"
#import "ImageModel.h"
#import "WMAboutBrandsViewController.h"

@interface MineViewController ()<UITableViewDelegate, UITableViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *iconImg;
@property (weak, nonatomic) IBOutlet UITableView *tbView;
@property (weak, nonatomic) IBOutlet UIButton *loginBtn;
@property(nonatomic, strong) NSArray<NSArray *> *datasource;
@end

@implementation MineViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationController.navigationBar setShadowImage:[[UIImage alloc] init]];  //去掉导航栏下的分割线
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:[UIColor colorWithHexString:@"ff8e01"] size:self.navigationController.view.frame.size] forBarMetrics:0];
    self.view.backgroundColor = [UIColor mainLightGrayColor];
    self.iconImg.layer.cornerRadius = 40;
    self.iconImg.layer.masksToBounds = YES;
    self.tbView.tableFooterView = [UIView new];
    self.tbView.bounces = NO;
    self.tbView.rowHeight = 58;
    [self setNavConfigStartColor:@"#ff8e01" endColor:@"#ff8e01"];
    [self ApptitileView:@"我的"];
    _datasource = @[@[@"我的预购记录", @"关于我们"], @[@"官方网址", @"客服热线"], @[@"设置"]];
    UITapGestureRecognizer *iconTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(loginEvent)];
    [self.iconImg addGestureRecognizer:iconTap];
    [self.tbView reloadData];
}
- (IBAction)loginEvent {
    if (![ShareValue sharedInstance].isLogin) {
        [self presentViewController:self.loginNav animated:YES completion:nil];
    } else {
        [SystemAlertView alertWithTitle:@"选择" message:nil preferredStyle:UIAlertControllerStyleActionSheet actionBtns:@[@"取消", @"拍照", @"从相册选择"] target:self btnClickBlock:^(NSString *actionTitle) {
            // 判断系统是否支持相机
            UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
            imagePickerController.delegate = self; //设置代理
            imagePickerController.allowsEditing = YES;
            NSUInteger sourceType = 0;
            if ([actionTitle isEqualToString:@"拍照"]) {
                if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                    sourceType = UIImagePickerControllerSourceTypeCamera;
                    imagePickerController.sourceType = sourceType;
                    [self presentViewController:imagePickerController animated:YES completion:nil];
                }else{
                    
                }
            } else if ([actionTitle isEqualToString:@"从相册选择"]) {
                if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]){
                    sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                    imagePickerController.sourceType = sourceType;
                    [self presentViewController:imagePickerController animated:YES completion:nil];
                }else{
                    
                }
            }
        }];
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    BOOL isLogin = [ShareValue sharedInstance].isLogin;
    self.iconImg.highlighted = isLogin;
    if (isLogin) {
        NSData *data = [[NSUserDefaults standardUserDefaults]objectForKey:@"image"];
        //在这里解档
        ImageModel *imgModel = [NSKeyedUnarchiver unarchiveObjectWithData:data];
        if (imgModel) {
            self.iconImg.image = imgModel.headImage;
            self.iconImg.highlightedImage = imgModel.headImage;
        }
        [self.loginBtn setTitle:[ShareValue sharedInstance].userName forState:UIControlStateNormal];
    } else {
        [self.loginBtn setTitle:@"点击登录" forState:UIControlStateNormal];
        self.iconImg.image = [UIImage imageNamed:@"头像2"];
        self.iconImg.highlightedImage = [UIImage imageNamed:@"头像1"];
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _datasource.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _datasource[section].count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
    }
    if (indexPath.section == 0 || indexPath.section == 2) {
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    } else {
        cell.detailTextLabel.textColor = [UIColor lightGrayColor];
        if (indexPath.row == 0) {
            cell.detailTextLabel.text = @"www.cp0069.com";
        } else {
            cell.detailTextLabel.text = @"0571-26201163";
        }
    }
    NSString *title = _datasource[indexPath.section][indexPath.row];
    cell.imageView.image = [UIImage imageNamed:title];
    cell.textLabel.text = title;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSString *title = _datasource[indexPath.section][indexPath.row];
    if ([title isEqualToString:@"设置"]) {
        [self performSegueWithIdentifier:@"MineViewController" sender:nil];
    } else if ([title isEqualToString:@"关于我们"]) {
        WMAboutBrandsViewController *controller = [WMAboutBrandsViewController new];
        controller.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:controller animated:YES];
    } else if([title isEqualToString:@"我的预购记录"]){ // 跳转到预购记录
        if ([ShareValue sharedInstance].isLogin) {
            OrderBillViewController *controller = [OrderBillViewController new];
            controller.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:controller animated:YES];
        }else{
            
            [self presentViewController:self.loginNav animated:YES completion:nil];
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 15;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return [UIView new];
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [UIView new];
    view.backgroundColor = [[UIColor lightGrayColor] colorWithAlphaComponent:0.1];
    return view;
}

#pragma mark -实现图片选择器代理-（上传图片的网络请求也是在这个方法里面进行，这里我不再介绍具体怎么上传图片）
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:^{}];
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage]; //通过key值获取到图片
    NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
    ImageModel *imgModel = [[ImageModel alloc] init];//这是一个自定义的对象
    imgModel.headImage = image;
    //不能直接存取NSObject，需要先归档转成NSData
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:imgModel];
    [defaults setObject:data forKey:@"image"];
    [defaults synchronize];
    _iconImg.image = image;  //给UIimageView赋值已经选择的相片
    _iconImg.highlightedImage = image;
}

//当用户取消选择的时候，调用该方法
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^{}];
}


- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    UIViewController *controller = segue.destinationViewController;
    controller.hidesBottomBarWhenPushed = YES;
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
